package com.atguigu.gulimall.auth.web;


import com.atguigu.common.utils.HttpClientUtils;
import com.atguigu.gulimall.auth.config.UcenterProperties;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * @author helen
 * @since 2020/5/4
 */
@Controller//注意这里没有配置 @RestController
@RequestMapping("/ucenter/wx")
@Slf4j
public class ApiWxController {

    @Autowired
    private UcenterProperties ucenterProperties;

    @Autowired
    private MemberFeignService memberService;

    @GetMapping("login")
    public String genQrConnect(HttpSession session){

        //组装url：https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=回调地址&response_type=code&scope=snsapi_login&state=随机数#wechat_redirect
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //将回调url进行转码
        String redirectUri = "";
        try {
            redirectUri = URLEncoder.encode(ucenterProperties.getRedirectUri(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //生成随机state，防止csrf攻击
        String state = UUID.randomUUID().toString();
        //将state存入session
        session.setAttribute("wx_open_state", state);

        String qrcodeUrl = String.format(
                baseUrl,
                ucenterProperties.getAppId(),
                redirectUri,
                state);


        //跳转到组装的url地址中去
            return "redirect:" + qrcodeUrl;
    }

    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session){
        

        if(StringUtils.isEmpty(code) || StringUtils.isEmpty(state)){
            log.error("非法回调请求");
        }

        String sessionState = (String)session.getAttribute("wx_open_state");
        if(!state.equals(sessionState)){
            log.error("非法回调请求");

        }


        //携带code临时票据，和appid以及appsecret请求access_token和openid（微信唯一标识）
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        //组装参数：?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        Map<String, String> accessTokenParam = new HashMap<>();
        accessTokenParam.put("appid", ucenterProperties.getAppId());
        accessTokenParam.put("secret", ucenterProperties.getAppSecret());
        accessTokenParam.put("code", code);
        accessTokenParam.put("grant_type", "authorization_code");
        HttpClientUtils client = new HttpClientUtils(accessTokenUrl, accessTokenParam);

        String result = "";
        try {
            //发送请求：组装完整的url字符串、发送请求
            client.get();
            //得到响应
            result = client.getContent();
            System.out.println("result = " + result);
        } catch (Exception e) {
            log.error("获取access_token失败");
        }
        Gson gson = new Gson();
        HashMap<String,Object> hashMap = gson.fromJson(result, HashMap.class);
        Object errorObject = hashMap.get("errcode");
        if(errorObject !=null) {
            Double errorcode = (Double) errorObject;
            log.error("获取access_token失败code"+errorcode+",message"+(String)hashMap.get("errmsg"));
        }
        //解析出结果的access_token和openid
        String accessToken = (String) hashMap.get("access_token");
        String openid = (String) hashMap.get("openid");
        //获取用户个人信息
        //在本地数据库查找当前用户信息直接使用微信用户信息
       // Member member = memberService.getByOpenId(openid);
        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo";
        //组装参数：?access_token=ACCESS_TOKEN&openid=OPENID
        Map<String, String> baseUserInfoParam = new HashMap<>();
        baseUserInfoParam.put("access_token", accessToken);
        baseUserInfoParam.put("openid", openid);
        client = new HttpClientUtils(baseUserInfoUrl, baseUserInfoParam);

        String resultUserInfo = "";
        try {
            client.get();
            resultUserInfo = client.getContent();
        } catch (Exception e) {
            e.printStackTrace();
        }

        HashMap<String, Object> resultUserInfoMap = gson.fromJson(resultUserInfo, HashMap.class);
        //失败的响应结果
        Object errcodeObj = resultUserInfoMap.get("errcode");
        if(errcodeObj != null){
            Double errcode = (Double)errcodeObj;
            String errmsg = (String)resultUserInfoMap.get("errmsg");
            log.error("获取用户信息失败：" + "code：" + errcode + ", message：" +  errmsg);
        }
        System.out.println("resultUserInfoMap"+resultUserInfoMap);
     

        return "redirect:http://gulimall.com";
        

      

    }


}
